package com.xiaoluo.web.k8;


import com.xiaoluo.common.utils.JsonUtils;
import com.xiaoluo.service.KubernetesService;
import com.xiaoluo.service.ServerService;
import com.xiaoluo.web.BaseController;
import com.xiaoluo.web.form.ResultForm;
import com.xiaoluo.web.form.ServiceForm;
import io.fabric8.kubernetes.api.model.*;
import io.fabric8.kubernetes.client.KubernetesClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.*;

/**
 * Project : SpiderManager
 * Package : com.xiaoluo.web
 * Created by Willian.
 * Date  : 2015/10/21 20:29.
 */
@Controller
@RequestMapping("/service")
public class ServiceController extends BaseController {
    private final static Logger logger = LoggerFactory.getLogger(ServiceController.class);

    @Autowired
    private ServerService serverService;
    @Autowired
    private KubernetesService kubernetesService;

    @RequestMapping(value = "/")
    public  String index(ModelMap model,String type){
        PodList pods = kubernetesService.getClient().pods().list();
        model.addAttribute("pods",pods);
        model.addAttribute("type",type);
        return "k8/services";
    }

    @RequestMapping(value = "/viewService",method = RequestMethod.GET)
    public  String viewService(ModelMap model,String namespace,String name){

        if(name !=null && !"".equals(name)){
            Service service = kubernetesService.getClient().services().inNamespace(namespace).withName(name).get();
            model.addAttribute("service",service);
        }

        model.addAttribute("nodes",kubernetesService.getClient().nodes().list());
        model.addAttribute("namespaces",kubernetesService.getClient().namespaces().list());
        return "k8/service/detail";
    }

    @RequestMapping(value = "/del")
    public  String del(ModelMap model,String namespace,String name){

        logger.info("User:{},del service:{} - {}",getCurrentUser().getUserName(),name,namespace);

        if(name !=null && !"".equals(name)){
            kubernetesService.getClient().services().inNamespace(namespace).withName(name).delete();
        }

        return "forward:/service/";
    }


    @RequestMapping(value = "/save",produces = "application/json; charset=UTF-8")
    @ResponseBody
    public ResultForm save(ModelMap model,@RequestBody String params){
        logger.info("User:{},save service:{}",getCurrentUser().getUserName(),params);

        ResultForm result = new ResultForm(0,"success");

        try {
            ServiceForm form = JsonUtils.mapper.readValue(params, ServiceForm.class);

            List<ServicePort> ports = new ArrayList<ServicePort>();
            ServicePort nodePort = new ServicePort();
            nodePort.setProtocol(form.getProtocol());

            if(form.getNodePort() !=0){
                nodePort.setNodePort(form.getNodePort());
            }

            if(form.getPort() !=0){
                nodePort.setPort(form.getPort());
            }

            if(form.getTargetPort() !=0){
                nodePort.setTargetPort(new IntOrString(form.getTargetPort()));
            }
            ports.add(nodePort);

            if(form.getOldName() != null && !"".equals(form.getName()))
                if (form.getOldName().equals(form.getName()) && form.getOldNamespace().equals(form.getNamespace())) {
                    //replace
                    DoneableService service = kubernetesService.getClient().inNamespace(form.getNamespace()).services().withName(form.getName()).edit();
                    if(form.getLabelsMap().size()>0){
                        service.editMetadata().withLabels(form.getLabelsMap());
                    }
                    if(form.getSelectorMap().size()>0){
                        service.editSpec().withSelector(form.getSelectorMap());
                    }
                    service.editSpec().getPorts().remove(0);
                    service.editSpec().withType(form.getType()).withClusterIP(form.getClusterIP()).withPorts(ports).endSpec();
                    service.done();
                } else {
                    //update

                    DoneableService service = kubernetesService.getClient().inNamespace(form.getOldNamespace()).services().withName(form.getOldName()).edit();
                    service.editMetadata().withName(form.getName()).withNamespace(form.getNamespace());
                    if(form.getLabelsMap().size()>0){
                        service.editMetadata().withLabels(form.getLabelsMap());
                    }
                    if(form.getSelectorMap().size()>0){
                        service.editSpec().withSelector(form.getSelectorMap());
                    }
                    service.editSpec().getPorts().remove(0);
                    service.editSpec().withType(form.getType()).withClusterIP(form.getClusterIP()).withPorts(ports).endSpec();
                    service.done();

                }
            else {
                //new
                EditableService service = new ServiceBuilder().withNewMetadata()
                        .withName(form.getName())
                        .withNamespace(form.getNamespace())
                        .withLabels(form.getLabelsMap())
                        .endMetadata()
                        .withNewSpec()
                        .withPorts(ports)
                        .withSelector(form.getSelectorMap())
                        .withLoadBalancerIP(form.getClusterIP())
                        .endSpec()

                        .build();
                kubernetesService.getClient().services().create(service);

            }

        } catch (IOException e) {
            e.printStackTrace();
            result.setMsg(e.getMessage());
            result.setCode(-1);
        }

        return result;
    }
}
